<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./node_modules/@tweenjs/tween.js/dist/tween.umd.js"></script>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background: pink;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <button id="start">开始</button>
    <button id="stop">停止</button>

    <script>
        const box = document.querySelector('#box');
        const start = document.querySelector('#start');
        const stop = document.querySelector('#stop');
        let requestAnimationId;
        // 创建动画实例
        let tween = tweenInit();
        // 创建动画实例方法
        function tweenInit() {
            // 创建动画实例
            const tween = new TWEEN.Tween({
                x: 0,
                y: 0
            });
            // 设置结束信息
            tween.to({
                x: 300,
                y: 200
            }, 1000);
            // 设置动画函数
            tween.easing(TWEEN.Easing.Quadratic.InOut)
            tween.repeat(2);
            tween.yoyo(true);
            tween.delay(10);
            tween.onStart(() => {
                console.log('start');
            });
            tween.onUpdate(({
                x,
                y
            }) => {
                console.log('update');
                box.style.setProperty('transform', 'translate(' + x + 'px, ' + y + 'px)')
            });

            tween.onComplete((obj) => {
                console.log(obj, 'complete');
            });

            tween.onStop(() => {
                console.log('stop');
            });
            return tween;
        }

        start.addEventListener('click', function () {
            // 激活tween实例, 如果没有激活, 不会执行动画
            tween.start();
            animate();
        });

        stop.addEventListener('click', function () {
            // 取消当前启动的requestAnimationFrame
            requestAnimationId > 0 && cancelAnimationFrame(requestAnimationId);
            tween.stop();
        });

        // Setup the animation loop.
        function animate() {
            // 如果动画已经结束,则返回false
            const result = TWEEN.update();
            requestAnimationId = requestAnimationFrame(animate)
            // 如果动画已经结束,则停止requestAnimationFrame
            if (!result) {
                cancelAnimationFrame(requestAnimationId)
            }
            console.log('animate');
        }
    </script>
</body>

</html>